#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <errno.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define SERV_PORT 9527

void sys_err(const char *str)
{
    perror(str);
    exit(1);
}
//UDP客户端
int main(int argc, char *argv[])
{
	int cfd; //客户端的文件描述符
	char buf[4096];
	int fret;

	struct sockaddr_in serv_addr; //服务器的地址结构，注意是服务器的
	bzero(&serv_addr, sizeof(serv_addr)); 
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons(SERV_PORT);//本地字节序转网络
	inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr.s_addr);//本地字节序转网络

	cfd = socket(AF_INET, SOCK_DGRAM, 0);
	if(cfd == -1)
		sys_err("client socket creat error");

	// bind(cfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr));//注意这里用bind没用
	//if(ret == -1)                       //注意这里不能检查返回值，否则会报错address already inuse ，和tcp是不同的
	//	sys_err("client bind error");

	while(fgets(buf, 4096, stdin) != NULL){
		fret = sendto(cfd, buf, strlen(buf), 0, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
		if (fret == -1)
			sys_err("client sendto error");

		fret = recvfrom(cfd, buf, sizeof(buf), 0, NULL, 0);//不关心对端信息
		if (fret == -1)
			sys_err("client recvfrom error");

		write(STDOUT_FILENO, buf,fret);
	}

	close(cfd);

    return 0;
}
